package com.imast.android.bys.service;

import static com.imast.android.bys.util.LogUtils.*;

import com.imast.android.bys.io.model.Usuario;
import com.imast.android.bys.ui.MainActivity;
import com.imast.android.bys.ui.Seguimiento;
import com.imast.android.bys.util.*;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

public class GCMIntentService extends IntentService {

	private static final String TAG = GCMIntentService.class.getSimpleName();
		
	private static final int NOTIF_ALERTA_ID = 1;
	
	public GCMIntentService() {
		super("GCMIntentService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		
		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
		 
        String messageType = gcm.getMessageType(intent);
        Bundle extras = intent.getExtras();
        
        if (!extras.isEmpty())
        {
                if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType))
                {
                	String operacion = extras.getString("operacion");
                	
                	
                	Log.d(TAG, operacion);
                	
                	switch (Integer.valueOf(operacion))
                	{
                		case 1:
                			enableGPS();
                			break;
                		case 2:
                			String msg = extras.getString("msg");
                			showNotification(msg);
                			break;
                		case 3:
                			double latitud = Double.parseDouble(extras.getString("latitud").replace(',', '.'));
                			double longitud = Double.parseDouble(extras.getString("longitud").replace(',', '.'));
                			showUbicacion(latitud, longitud);
                			break;
                	}
                } else if (intent.getExtras().containsKey("registration_id")) {
                	registerGCMId(intent, getApplicationContext());
                }
        }
		
	}
	
	private void registerGCMId(Intent intent, Context context) {
		
		String regId = intent.getExtras().getString("registration_id");
		if(regId != null && !regId.equals("")) {
			Log.d(TAG, "New GCM ID : " + regId);
			
			SessionManager sm = new SessionManager(getApplicationContext());
			Usuario userData = sm.getUserDetails();
			
			String user = userData.getUser();
			
			if (TextUtils.isEmpty(user)) {
				LOGD(TAG, "Falta Configurar el Usuario");
				return;
			}
			
			boolean registrado = GCMUtils.registroServidor(context, user, regId);
			
			if (registrado)
			{
				GCMUtils.storeRegistrationId(context, user, regId);
			}
			
		}
		
	}
	
	private void showNotification(String msg)
    {
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 
        NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                .setSmallIcon(android.R.drawable.stat_sys_warning)
                .setContentTitle("ByS")
                .setContentText(msg);
        
        long[] pattern = {500,500,500,500,500,500,500,500,500};        
        mBuilder.setVibrate(pattern);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);
 
        Intent notIntent =  new Intent(this, MainActivity.class);
        PendingIntent contIntent = PendingIntent.getActivity(
                this, 0, notIntent, 0);
 
        mBuilder.setContentIntent(contIntent);
 
        mNotificationManager.notify(NOTIF_ALERTA_ID, mBuilder.build());
    }
	
	private void showUbicacion(double latitud, double longitud)
    {
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 
        NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                .setSmallIcon(android.R.drawable.stat_sys_warning)
                .setContentTitle("ByS - Tracking")
                .setContentText(latitud + "," + longitud);
        
        long[] pattern = {500,500,500,500,500,500,500,500,500};        
        mBuilder.setVibrate(pattern);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);
 
        Intent notIntent =  new Intent(this, Seguimiento.class);
        notIntent.putExtra("latitud", latitud);
        notIntent.putExtra("longitud", longitud);
        
        
        PendingIntent contIntent = PendingIntent.getActivity(
                this, 0, notIntent, 0);
 
        mBuilder.setContentIntent(contIntent);
 
        mNotificationManager.notify(NOTIF_ALERTA_ID, mBuilder.build());
        
        Intent intent = new Intent("com.imast.android.bys.myBroadcast");
        // add data
        intent.putExtra("latitud", latitud);
        intent.putExtra("longitud", longitud);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        
    }
    
    private void enableGPS()
    {
    	HelperUtils.enableGPS(getApplicationContext(), true);
    }

}
